﻿#include "cimagedownloader.h"
#include "CGlobal.h"
#include <QLabel>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPixmap>
#include <QDebug>
#include <QEventLoop>
#include <QTimer>
#include <QPainter>
#include <QAuthenticator>

CImageDownloader::CImageDownloader(QLabel* label, const QString& imageUrl,
	const QString& username, const QString& password,
	QObject* parent)
	: QObject(parent)
	, m_imageLabel(label)
	, m_sImageUrl(imageUrl)
	, m_networkManager(nullptr)
	, m_currentReply(nullptr)
	, m_username(username)
	, m_password(password)
	, m_isAuthenticated(false)
{
	initNetworkManager();
}


CImageDownloader::CImageDownloader(const QString& imageUrl,
	const QString& username, const QString& password,
	QObject* parent)
	: QObject(parent)
	, m_imageLabel(nullptr)
	, m_sImageUrl(imageUrl)
	, m_networkManager(nullptr)
	, m_currentReply(nullptr)
	, m_username(username)
	, m_password(password)
	, m_isAuthenticated(false)
{
	initNetworkManager();
}

CImageDownloader::~CImageDownloader()
{
	cancelDownload();
	delete m_networkManager;
	m_networkManager = nullptr;
}

bool CImageDownloader::getNewDlPixmap(QPixmap &newPixmap, int timeoutMs /*= 5000*/)
{
	if (m_sImageUrl.isEmpty()) {
		qWarning() << "Image URL is empty";
		return false;
	}

	cancelDownload(); // 确保没有进行中的下载

	QNetworkRequest request = createRequest();
	m_currentReply = m_networkManager->get(request);

	QEventLoop loop;
	QTimer timer;
	timer.setSingleShot(true);

	// 连接信号
	connect(m_currentReply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
	connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);

	timer.start(timeoutMs);
	loop.exec();

	bool success = false;

	if (m_currentReply->isFinished()) {
		success = processReply(m_currentReply, newPixmap);
	}
	else {
		qWarning() << "Download timeout or cancelled";
	}

	m_currentReply->deleteLater();
	m_currentReply = nullptr;

	return success;
}

void CImageDownloader::setCredentials(const QString& username, const QString& password)
{
	m_username = username;
	m_password = password;
	m_isAuthenticated = !username.isEmpty();
}

void CImageDownloader::downloadAsync()
{
	if (m_currentReply) {
		cancelDownload();
	}

	QNetworkRequest request = createRequest();
	m_currentReply = m_networkManager->get(request);

	connect(m_currentReply, &QNetworkReply::finished,
		this, &CImageDownloader::slotOnImageDownloaded);

	// 设置超时
	QTimer::singleShot(10000, this, [this]() {
		if (m_currentReply && m_currentReply->isRunning()) {
			m_currentReply->abort();
		}
	});
}

void CImageDownloader::cancelDownload()
{
	if (m_currentReply) {
		m_currentReply->disconnect();
		m_currentReply->abort();
		m_currentReply->deleteLater();
		m_currentReply = nullptr;
	}
}

void CImageDownloader::slotOnImageDownloaded()
{
	QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
	if (!reply) {
		return;
	}

	QPixmap pixmap;
	bool success = processReply(reply, pixmap);

	if (success) {
		emit downloadFinished(pixmap);

		// 如果设置了QLabel，更新显示
		if (m_imageLabel) {
			QPixmap scaledPixmap = pixmap.scaled(m_imageLabel->size(),
				Qt::KeepAspectRatio,
				Qt::SmoothTransformation);
			m_imageLabel->setPixmap(scaledPixmap);
			m_imageLabel->setScaledContents(true);
		}
	}

	reply->deleteLater();
	m_currentReply = nullptr;
}

void CImageDownloader::onAuthenticationRequired(QNetworkReply* reply, QAuthenticator* authenticator)
{
	Q_UNUSED(reply);

	if (!m_username.isEmpty() && !m_password.isEmpty()) {
		// 使用预先设置的凭据
		authenticator->setUser(m_username);
		authenticator->setPassword(m_password);
		m_isAuthenticated = true;
	}
	else {
		// 发出需要认证的信号
		emit authenticationRequired(authenticator->realm());
		// 取消认证，等待外部提供凭据
		authenticator->setUser("");
		authenticator->setPassword("");
	}
}

void CImageDownloader::onSslErrors(QNetworkReply* reply, const QList<QSslError>& errors)
{
	Q_UNUSED(errors);
	// 忽略SSL错误（适用于自签名证书）
	reply->ignoreSslErrors();
}

void CImageDownloader::initNetworkManager()
{
	m_networkManager = new QNetworkAccessManager(this);

	// 连接认证信号
	connect(m_networkManager, &QNetworkAccessManager::authenticationRequired,
		this, &CImageDownloader::onAuthenticationRequired);

	// 连接SSL错误信号
	connect(m_networkManager, &QNetworkAccessManager::sslErrors,
		this, &CImageDownloader::onSslErrors);
}

QNetworkRequest CImageDownloader::createRequest() const
{
	QNetworkRequest request;
	request.setUrl(QUrl(m_sImageUrl));

	// 设置请求头
	request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
	request.setRawHeader("Accept", "image/webp,image/*,*/*;q=0.8");
	request.setRawHeader("Connection", "Keep-Alive");

	// 添加Basic认证头（如果已有凭据）
	if (!m_username.isEmpty() && !m_password.isEmpty()) {
		addBasicAuthHeader(request);
	}

	// 配置SSL（忽略错误，适用于自签名证书）
	QSslConfiguration sslConfig = request.sslConfiguration();
	sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
	request.setSslConfiguration(sslConfig);

	return request;
}

bool CImageDownloader::processReply(QNetworkReply* reply, QPixmap& resultPixmap)
{
	if (reply->error() == QNetworkReply::NoError) {
		QByteArray imageData = reply->readAll();

		// 检查是否是有效的图片数据
		if (imageData.size() > 0) {
			if (resultPixmap.loadFromData(imageData)) {
				return true;
			}
			else {
				qWarning() << "Failed to load image from data";
				emit downloadFailed("Invalid image data");
			}
		}
		else {
			qWarning() << "Empty response received";
			emit downloadFailed("Empty response");
		}
	}
	else {
		QString errorMsg = QString("Network error: %1 (code: %2)")
			.arg(reply->errorString())
			.arg(reply->error());
		qWarning() << errorMsg;
		emit downloadFailed(errorMsg);
	}

	return false;
}

void CImageDownloader::addBasicAuthHeader(QNetworkRequest& request) const
{
	QString credentials = m_username + ":" + m_password;
	QByteArray base64Credentials = credentials.toUtf8().toBase64();
	request.setRawHeader("Authorization", "Basic " + base64Credentials);
}
